<template>
  <div class="serviceList flex-column">
    <h4 class="serviceTitle listTitle">客服列表</h4>
    <p class="serviceNumer">当前共计{{ (accountListMap[uistate.adminid]||[]).length }}名客服账号</p>
    <ul class="scrollAuto ">
      <service-list-item
        :currentServiceWxId="currentService.wxid"
        :accountid="item"
        :showBadge="true"
        @click="changeCurrentService(item)"
        @editServiceInfo="openDialog(item)"
        v-for="(item, i) in (accountListMap[uistate.adminid]||[])" :key="i"
      ></service-list-item>
    </ul>
    <div class="addAccountBox">
      <!-- <button class="layui-btn layui-btn-normal layui-btn-sm addAccount" @click="syncAccount">同步账号</button> -->
    </div>
    <modal name="changeInfoDialog" 
        transition="nice-modal-fade"
        overlayTransition="overlay-fade"
        draggable=".el-card__header" :width="400" height="auto">
        <el-card class="box-card">
          <div slot="header" class="clearfix" style="display: flex; flex-direction: row;justify-content: space-between;">
            <span>修改信息<span>（修改后5分钟内生效）</span></span>
            <i class="el-icon-close" @click.stop="$modal.hide('changeInfoDialog')"></i>
          </div>
          <div>
            <el-form ref="form" label-width="70px"> 
              <el-form-item label="名称">
                <el-input placeholder="" :value="form.nick" @input="changeForm('nick', $event )" clearable></el-input>
              </el-form-item> 
              <el-form-item label="头像">
                <div class="change-info-avatar">
                  <div class="change-info-avatar-icon">
                    <i class="el-icon-edit"></i>
                    <input type="file" accept=".png, .jpg, .jpeg" @change="changeForm('avatar', $event , $event)">
                  </div>
                  <el-avatar shape="square" :size="40" :src="form.tempUrl" style="vertical-align: middle;" />
                </div>
                 
              </el-form-item> 
              <el-form-item label="性别">

                <el-radio-group :value="form.gender" size="small">
                  <el-radio :label="1" @change="changeForm( 'gender', 1)">男</el-radio>
                  <el-radio :label="2" @change="changeForm( 'gender', 2)">女</el-radio>
                </el-radio-group>

              </el-form-item>
               <el-form-item label="个性签名">
                <el-input placeholder="" :value="form.signature" @input="changeForm( 'signature', $event )" clearable></el-input>
              </el-form-item> 
              <el-form-item>
                <el-button type="primary" @click="submitServiceInfo">确定</el-button>
                <el-button @click.stop="$modal.hide('changeInfoDialog')">取消</el-button>
              </el-form-item>

            </el-form>
          </div> 
        </el-card>
    </modal>
     
  </div>
</template>
<script>
import { mapState, mapActions, mapMutations } from 'vuex'
import ServiceListItem from '@/components/serviceListItem'
import CustomDialog from '@/components/customDialog'
import { Promise } from 'q';

export default {
  name: 'serviceList',
  mounted() {
    const {group} = this.$route.params
    if (group) {
      return this.sortedServices.map(s=>{
        if (s.wxid == group.csid) {
          this.setCurrentService(s)
        }
      })
    }
    this.setCurrentService(this.sortedServices[0])
  },
  data() {
    return {
      showDialog: false,
      form: {},
      selectAccount:{}
    }
  },
  components: {
    ServiceListItem,
    CustomDialog
  },
  computed: {
    ...mapState([
      'services', 
      //================ 
      'uistate',
      'accountListMap',
      'accountMap'
      ]),
      currentService(){
        const { accountid } = this.uistate;
        const account = this.accountMap[accountid]
        return account   
      },  
    sortedServices() {
      if (!this.services) return [];
      let services = JSON.parse(JSON.stringify(this.services));
      services.sort((a,b)=>{
        if (a.always_top && b.always_top) {
          return 0
        } else if (a.always_top && !b.always_top){
          return -1
        } else {
          return 0
        }
      })
      return services;
    },
  },
  methods: {
    ...mapMutations(['setCurrentService']),
    ...mapActions(['updateWxAccount']),
    openDialog(item) {
      this.selectAccount = this.accountMap[item]

      this.form = {
        nick:this.selectAccount.nick,
        tempUrl:this.selectAccount.avatar,
        signature:this.selectAccount.signature,
        gender:this.selectAccount.gender
      }
      // this.showDialog = true

      this.$modal.show('changeInfoDialog')
    },
    syncAccount(){
      this.$msg('待实现')
    },
    addAccount() {

    },
    changeCurrentService(service) {
      this.setCurrentService(service);
    },
    getDataUrl(file){
      const fr = new FileReader()
      fr.readAsDataURL(file)
      return new Promise((resolve,reject)=>{
        fr.onload = e =>{
          resolve(fr.result)
        }        
      })
      
    },
    async changeForm(key, val, e) {
      let file, tempUrl;
      if (e && e.target && e.target.files) {
        file = e.target.files[0]
        tempUrl = window.URL.createObjectURL(file);
        // const res = await this.uploadFile(file,{})
        const result = await this.getDataUrl(file)
         
        this.$set(this.form,key,result.replace(/data:image\/(png|jpeg);base64,/gi, ''))
        this.$set(this.form,'tempUrl',tempUrl)

        return;
      }
      
      this.$set(this.form, key,val)
    },
    submitServiceInfo() {
      const { wxid,id,csid } = this.selectAccount;
      this.form.wxid = wxid
      this.form.id = id
      let params = {
        id,
        csId:csid,
        accountWxid:wxid,
        gender: this.form.gender,
        signature: this.form.signature,
        nickname:this.form.nick,
        nick:this.form.nick,
        imagedata:this.form.avatar,
        avatar:this.form.tempUrl,
        area:this.form.area
      }
       
      this.updateWxAccount(JSON.parse(JSON.stringify(params))  )
      .then(()=>{
        this.$message({
          showClose: true,
          message: '提交成功',
          type: 'success'
        });
        this.$modal.hide('changeInfoDialog')
        this.form = {}
      })
      
    }
  }
}
</script>
<style scoped>
 .change-info-upload{
   position: relative;
   display: inline-block;
   width: 80px;
   text-align: center;
 }
 .change-info-avatar-icon input{
   width: 100%;
   height: 100%;
   position: absolute;
   top:0;
   left: 0;
   right: 0;
   bottom: 0;
   opacity: 0;
 }
 .change-info-avatar-icon{
   position: absolute;
   top:0;
   left: 0;
   right: 0;
   bottom: 0;
   width:100%;
   height:100%;
   text-align: center;
   line-height: 40px;
   border: 1px solid #409eff;
   display: none;
   border-radius: 3px;
   font-size: 18px;
   color: #409eff;
   background: rgba(255,255,255,.7);
   box-sizing: border-box;
 }
 .change-info-avatar{
    width:40px;
    height:40px;  
    position: relative;
 }
 .change-info-avatar:hover .change-info-avatar-icon{
   display: block;
 }

</style>
